<template>
	<view class="container">
		<customNav>
			<view style="display: flex; align-items: center;" @click="handleToHome">
				<uni-icons type="left" size="28"></uni-icons>
				<text class="size18" style="margin-left: 16rpx;">温控器</text>
			</view>
		</customNav>
		<view class="content">
			<view style="display: flex;align-items: center;justify-content: center;margin-top: 10px;">
				<img :src="wenkongqiUrl" style="width:198px;height: 198px;" alt="" />
			</view>
			<view style="width: 100%;height: 100px;display: flex;align-items: center;justify-content: center;">
				<view class="info-box">
					<view class="info-box-item" :style="{width:qe != null ? '25%' : '33.3%'}">
						<view class="size14">实时温度</view>
						<view style="height: 30px;" class="size14 margin-t4">{{temp_current}}℃</view>
					</view>
					<view class="info-box-item" :style="{width:qe != null ? '25%' : '33.3%'}">
						<view class="size14">设备开关</view>
						<view style="height: 30px;" class="margin-t4">
							<u-switch v-model="device_switch" @change="changeSwitch"></u-switch>
						</view>
					</view>
					<view class="info-box-item" :style="{width:qe != null ? '25%' : '33.3%'}">
						<view class="size14">设备状态</view>
						<view style="height: 30px;" class="size14 margin-t4">{{work_state}}</view>
					</view>
					<view v-if="qe!=null"  class="info-box-item" :style="{width:qe != null ? '25%' : '33.3%'}">
						<view class="size14">电池电量</view>
						<view style="height: 30px;" class="size14 margin-t4">{{qe}}%</view>
					</view>
				</view>
			</view>
			<view style="padding:0 20px;width: 100%;box-sizing: border-box;margin-top: 20px;">
				<view class="white-bg1">
					<view style="width: 100%;display: flex;align-items: center;justify-content: space-between;">
						<img src="@/static/images/jian.png" style="width:28px;height:28px" alt="" @click="jianClick" />
						<view class="bold" style="width:calc(100% - 60px);text-align: center;font-size: 36px;">
							{{currentValue}}℃
						</view>
						<img src="@/static/images/jia.png" style="width:28px;height:28px" alt="" @click="jiaClick" />
					</view>
					<view style="width: 100%;" class="margin-t20">
						<u-line-progress :percentage="getProgross(currentValue)" activeColor="#409eff" :showText="false"
							height="15"></u-line-progress>
					</view>
				</view>
				<view class="size14 margin-b10 margin-t10">分配房间</view>
				<view class="white-bg" @click="selectRoom(0)" style="display: flex;align-items: center;justify-content: space-between;">
					<view class="size14">客厅</view>
					<uni-icons v-if="currentRoom == 0" type="checkmarkempty" size="30" color="#007aff"></uni-icons>
				</view>
				<view class="white-bg" @click="selectRoom(1)" style="display: flex;align-items: center;justify-content: space-between;">
					<view class="size14">主卧</view>
					<uni-icons v-if="currentRoom == 1" type="checkmarkempty" size="30" color="#007aff"></uni-icons>
				</view>
				<view class="white-bg" @click="selectRoom(2)" style="display: flex;align-items: center;justify-content: space-between;">
					<view class="size14">次卧</view>
					<uni-icons v-if="currentRoom == 2" type="checkmarkempty" size="30" color="#007aff"></uni-icons>
				</view>
			</view>
		</view>
		<!-- 自定义底部 tabbar -->
		<CustomTabbar :tabList="list" :currentIndex="current" @tabChange="handleTabChange" />
		<uni-popup ref="popupRef" :mask-click="false" border-radius="10px 10px 0 0">
			<view style="width:300px;background-color: #ffffff;border-radius: 20px;padding: 30px 20px 10px 20px;box-sizing: border-box
		;">
				<view class="size18" style="color: #333333;font-weight: bold;">修改设备别名</view>
				<view class="size14" style="color: #333333;margin-top: 15px;">请输入设备别名：例如客厅</view>
				<input class="uni-input" v-model="set_alias"
					style="border-bottom: 1px solid #666666;margin-top: 10px;padding: 10px 0;" maxlength="50"
					placeholder="请输入设备别名" />
				<view style="display: flex;align-items: center;justify-content: flex-end;margin-top: 10px;">
					<view class="size14" @click="closePopupClick" style="padding: 10px;box-sizing: border-box
				;">取消</view>
					<view class="size14" @click="modifyDeviceClick" style="margin-left: 15px;color: #3c9cff;padding: 10px;box-sizing:border-box 
				;">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { eventBus } from '@/utils/bus/index.js';
	import env from "@/config/env.js";
	import customNav from "@/components/nav/index.vue"
	import CustomTabbar from '@/components/tab/index.vue';
	import {
		modifyDevice,
		deviceToHome
	} from "@/api/device/index.js";
	export default {
		components: {
			customNav,
			CustomTabbar
		},
		data() {
			return {
				wenkongqiUrl: env.baseUrl + "/file/get_file?file_name=温控器.png",
				inPage: false,
				currentValue: 26, // 当前设定温度值
				currentRoom: 0,
				list: [{
						icon: 'home-filled',
						text: '舒适',
						color: '#999',
						activeColor: '#007aff'
					},
					{
						icon: 'list',
						text: '在家',
						color: '#999',
						activeColor: '#007aff'
					},
					{
						icon: 'person-filled',
						text: '离家',
						color: '#999',
						activeColor: '#007aff'
					},
					{
						icon: 'compose',
						text: '编辑',
						color: '#999',
						activeColor: '#007aff'
					}
				],
				current: 0,

				set_alias: "",
				unit_uuid: "",

				device_switch: false, //设备开关
				temp_current: "26", //当前温度
				work_state: "加热", //设备状态
				qe:null, //电池电量

				webSocket: null,
			};
		},
		onReady() {
			
		},
		onLoad(options) {
			this.currentRoom = options.pactNumber ? Number(options.pactNumber) - 1 : -1
			this.unit_uuid = options.setUuid
			this.initWebSocket()
		},
		onShow() {
			this.inPage = true;
		},
		onUnload() {
			// 在页面销毁时关闭 WebSocket 连接
			if (this.webSocket) {
				this.webSocket.close({
					success: () => {
						console.log('主动关闭成功');
						this.webSocket = null;
						this.inPage = false;
					},
					fail: (err) => console.error('关闭失败:', err)
				});
			}
		},
		methods: {
			handleToHome() {
				uni.navigateBack({
					delta: 1
				});
			},
			handleTabChange(id) {
				if (id == 3) {
					this.modifyDevice()
				} else {
					// this.current = id
					//向设备发送温度
					const message =
						`web_col://sn=${this.unit_uuid}&col={"pl_versions":4,"pl_json":{"device_mode":"${id == 0 ?"manual" :id == 1 ? "home" :id == 2 ? "leave" : "manual"}","device_sn":"${this.unit_uuid}"}}`; // 构造发送的数据
					this.sendData(message); // 连接发送数据
				}
			},
			getProgross() {
				let pross = (((this.currentValue - 5) / (35 - 5)) * 100).toFixed(0);
				return pross;
			},
			//减少温度
			jianClick() {
				if (this.currentValue == 0) {
					return;
				}
				this.currentValue = this.currentValue - 1;
				//向设备发送温度
				const message =
					`web_col://sn=${this.unit_uuid}&col={"pl_versions":4,"pl_json":{"temp_set":"${this.currentValue.toFixed(0)}","device_sn":"${this.unit_uuid}"}}`; // 构造发送的数据
				this.sendData(message); // 连接发送数据
			},
			//增加温度
			jiaClick() {
				if (this.currentValue == 35) {
					return;
				}
				this.currentValue = this.currentValue + 1;
				//向设备发送温度
				const message =
					`web_col://sn=${this.unit_uuid}&col={"pl_versions":4,"pl_json":{"temp_set":"${this.currentValue.toFixed(0)}","device_sn":"${this.unit_uuid}"}}`; // 构造发送的数据
				this.sendData(message); // 连接发送数据
			},
			//设备开关操作
			changeSwitch(status) {
				// this.device_switch = status
				//向设备发送开关
				const message =
					`web_col://sn=${this.unit_uuid}&col={"pl_versions":4,"pl_json":{"device_switch":"${status ? 1 : 0}","device_sn":"${this.unit_uuid}"}}`; // 构造发送的数据
				this.sendData(message); // 连接发送数据
			},
			//点击编辑设备
			modifyDevice() {
				this.set_alias == "";
				this.$refs.popupRef.open('center');
			},
			//取消添加设备
			closePopupClick() {
				this.$refs.popupRef.close();
			},
			//绑定设备接口
			async modifyDeviceClick() {
				if (this.set_alias == "") {
					uni.showToast({
						title: "请输入设备别名",
						icon: "none"
					});
					return false;
				}
				let params = {
					set_alias: this.set_alias,
					unit_uuid: this.unit_uuid
				}
				const res = await modifyDevice(params);
				if (res.status == 200) {
					this.closePopupClick();
				} else {
					uni.showToast({
						title: res.msg,
						icon: "none"
					});
				}
			},

			//实时通讯
			initWebSocket() {
				const wsUrl = env.wsUrl; // 修正 URL 格式，添加双斜杠
				// 使用 uni.connectSocket 建立 WebSocket 连接
				this.webSocket = uni.connectSocket({
					url: wsUrl,
					success: () => {
						console.log('WebSocket 连接发起成功');
					},
					fail: (err) => {
						console.error('WebSocket 连接发起失败:', err);
						uni.showToast({
							title: '连接失败',
							icon: 'none',
							duration: 2000,
						});
					},
				});

				// 监听 WebSocket 连接成功打开事件
				this.webSocket.onOpen(() => {
					console.log('WebSocket 连接已打开');
					const message = `web_sub://sn=${this.unit_uuid}`; // 构造发送的数据
					this.sendData(message); // 连接打开后立即发送数据
				});

				// 监听 WebSocket 接收到消息事件
				this.webSocket.onMessage((event) => {
					console.log('从服务器收到数据:', event.data);
					if (event.data === `UNIT_OUT://sn=${this.unit_uuid}`) {
						uni.showToast({
							title: '设备离线',
							icon: 'error',
							duration: 2000,
						});
					} else if (event.data === `UNIT_LOGIN://sn=${this.unit_uuid}`) {
						const message =
							`web_col://sn=${this.unit_uuid}&col={"pl_versions":4,"pl_json":{"device_data":"1","device_sn":"${this.unit_uuid}"}}` // 构造发送的数据
						this.sendData(message)
					} else if (this.isJsonString(event.data)) {
						let data = JSON.parse(event.data);
						this.setData(data);
					} else {
						console.log('收到的数据不是合法的 JSON 格式:', event.data);
					}
				});

				// 监听 WebSocket 连接发生错误事件
				this.webSocket.onError((error) => {
					console.error('WebSocket 错误:', error);
					uni.showToast({
						title: '服务器异常',
						icon: 'none',
						duration: 2000,
					});
				});

				// 监听 WebSocket 连接关闭事件
				this.webSocket.onClose(() => {
					console.log('WebSocket 连接已关闭');
					// 可以选择在这里重新连接
					if (this.inPage) {
						setTimeout(() => {
							this.initWebSocket();
						}, 5000);
					}
				});
			},
			//是否为json字符串
			isJsonString(str) {
				try {
					JSON.parse(str);
					return true;
				} catch (e) {
					return false;
				}
			},
			sendData(message) {
				if (this.webSocket) {
					this.webSocket.send({
						data: message,
						success: () => {
							console.log('数据发送成功:', message);
						},
						fail: (err) => {
							console.error('数据发送失败:', err);
						},
					});
				} else {
					console.error('WebSocket 未连接');
				}
			},
			setData(data) {
				this.work_state = data.pl_json.work_state == "unheating" ? "空闲":"加热"; //设备状态
				this.temp_current = data.pl_json.temp_current; //实时温度
				this.device_switch = data.pl_json.device_switch == 1; //设备开关
				this.currentValue = Number(data.pl_json.temp_set); //当前温度
				this.qe = data.pl_json.qe; //当前温度
				this.current = (data.pl_json.device_mode == "manual") ? 0 : (data.pl_json.device_mode == "home") ? 1 : (data.pl_json) ? 2 : 0; //当前模式是舒适、在家还是离家
			},
			
			selectRoom(index){
				this.currentRoom = index
				this.menuItemClick(index + 1)
			},
			//底部菜单（第一个菜单）选择事件
			async menuItemClick(item) {
				console.log('点击了：', item);
				// 调用设备分配房间接口
				let params = {
					uuid:  this.unit_uuid,
					pactNumber: item,
				}
				const res = await deviceToHome(params);
				if (res.status == 200) {
					uni.showToast({
						title: "分配成功",
						icon: "none"
					});
					// 触发事件通知首页更新
					eventBus.emit('deviceGroupUpdated', {
					  setUuid: this.unit_uuid,
					  pactNumber: item
					});
				} else {
					uni.showToast({
						title: res.msg,
						icon: "none"
					});
				}
			},
		}
	};
</script>

<style scoped>
	.container {
		width: 100%;
	}

	.content {
		width: 100%;
		display: flex;
		align-items: center;
		flex-flow: column;
	}

	.canvas-box {
		width: 270px;
		height: 270px;
		background-color: #409eff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.gauge-canvas {
		width: 200px;
		height: 200px;
	}

	.info-box {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 90%;
		height: 80px;
		background-color: #409eff;
		border-radius: 20px;
		color: #ffffff;
	}

	.info-box-item {
		display: flex;
		align-items: center;
		flex-flow: column;
		justify-content: center;
		width: 25%;
	}

	.white-bg1 {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-radius: 10px;
		background-color: #ffffff;
		margin-bottom: 10px;
		padding: 10px;
		box-sizing: border-box;
		flex-flow: column;
	}
	.white-bg {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-radius: 10px;
		background-color: #ffffff;
		margin-bottom: 10px;
		padding: 0 10px;
		height: 50px;
		box-sizing: border-box;
	}
</style>